;(function($){
	$.extend($.jgrid,{});

	$.jgrid.extend({
		/**
		 * 行双击事件
		 */
		ondblClickRow : function(idVal,rowNum,colNum, event){
			var grid = this,_this = $(grid);
			//1.翻页前事件
			if($.isFunction(grid.p.beforeDblClickRow)){
				if(!grid.p.beforeDblClickRow.call(grid,idVal,rowNum,colNum,event)){
					return false;
				}
			}
			//2.弹出层式编辑
			if(grid.p.dblClickRowOpenEditWindow === true){
				_this.jqGrid("openEditWindow");
			}
//			alert(idVal);
//			alert(rowNum);
//			alert(colNum);
//			alert($(event.target).html());
		},
		/**
		 * 行选择前事件
		 */
		beforeSelectRow : function(rowId,event){
			var grid = this,_this = $(grid),$target = $(event.target);
			//点击复选框
			if($target.is('input:checkbox')){
				//恢复正在编辑的单元格到不可编辑状态
				_this.jqGrid("restoreCellStatus");
			}
			//行点击前事件
			if($.isFunction(grid.p.beforeSelectRowFunc)){
				if(!grid.p.beforeSelectRowFunc.call(grid,rowId,event))
					return false;
			}
			//
			var rowData = _this.jqGrid("getRowDataById",rowId);
			
			//如果启用表格内编辑，需要恢复正在编辑的单元格到不可编辑状态
			if(grid.p.cellEdit === true){
				//防重复点击相同单元格
				if(rowId != _this.jqGrid("getCurrentSelectRowId")){
					_this.jqGrid("restoreCellStatus");
					//表格内编辑的校验
					if(!_this.jqGrid("validateCellDatas",_this.jqGrid("getSaveRowDatas"))){
						//复选框：1.新增状态,不允许反选;2.新增状态,修改状态,不通过校验不能反选;3.新增一条不通过校验,其它行不能点
						$target.attr("checked",false);
						event.stopPropagation();
						return false;
					}
					//判断当前行是否已经选中，防止重复选中
					if(grid.p.multiselect && !$target.is('input:checkbox')){
						if(grid.p.multiboxonly===true){
							_this.jqGrid('resetSelection');
						}
						_this.jqGrid("setSelection",rowId,true);
					}
				}else if(rowId == _this.jqGrid("getCurrentSelectRowId")){
					//复选框：1.新增状态,不允许反选;2.新增状态,修改状态,不通过校验不能反选;3.新增一条不通过校验,其它行不能点
					if($target.is('input:checkbox') &&
							(rowData.rowStatus == Gfa.GlobalConstant.ROWSTATUS_MODIFIED 
									|| rowData.rowStatus == Gfa.GlobalConstant.ROWSTATUS_ADDED)){
						$target.attr("checked",true);
						event.stopPropagation();
						return false;
					}
				}
			}else{
//				alert($.objToJSONString(rowData));
				if(rowId == _this.jqGrid("getCurrentSelectRowId")){
					if($target.is('input:checkbox') &&
							(rowData.rowStatus == Gfa.GlobalConstant.ROWSTATUS_MODIFIED 
									|| rowData.rowStatus == Gfa.GlobalConstant.ROWSTATUS_ADDED)){
						//复选框：1.新增状态,不允许反选;2.新增状态,修改状态,不通过校验不能反选;3.新增一条不通过校验,其它行不能点
						if (grid.p.editFormSelector) {
							if (grid.p.enabledValidateForm) {
								if (!$.jqValidator.validateForm(grid.p.editFormSelector)) {
									$target.attr("checked", true);
									event.stopPropagation();
									return false;
								}
							}
						}
					}
				}else if(rowId != _this.jqGrid("getCurrentSelectRowId")){
					//验证表单
					//alert("beforeSelectRow是否验证："+grid.p.enabledValidateForm);
					if(grid.p.editFormSelector){
						if(grid.p.enabledValidateForm){
							if(!$.jqValidator.validateForm(grid.p.editFormSelector)){
								//复选框：1.新增状态,不允许反选;2.新增状态,修改状态,不通过校验不能反选;3.新增一条不通过校验,其它行不能点
								$target.attr("checked",false);
								event.stopPropagation();
								return false;
							}
						}
						//alert("beforeSelectRow通过.");
					}
				}
			}
			
			return true;
		},
		/**
		 * 行选择事件
		 */
		onSelectRow : function (rowid, selected,event){
			//alert(rowid+" , "+selected);
			var grid = this,_this = $(this);
			//add by baodk允许多行选中时,grid中单独选中所有数据表头全选框要选中
			if(grid.p.multiselect === true && _this.jqGrid('getGridParam','selarrrow').length == grid.p.reccount){
				$("#cb_" + grid.p.id).attr("checked", "checked");
			}
			//按钮状态
			_this.jqGrid('refreshButtonStatus');
			//1.表格到表单GridToForm
			
			var $editFormSelector = $(grid.p.editFormSelector);
			if($editFormSelector.length> 0 && selected===true){
				//1.1.弹出层式编辑
				if (grid.p.selectRowOpenEditWindow === true && grid.p.dblClickRowOpenEditWindow === false && event && $.isPlainObject(grid.p.editWindow) && !$.isEmptyObject(grid.p.editWindow)) {
					//判断点击的是否是行的'复选框','删除动作列','自定义动作列',就不需要弹出编辑窗体
					var target = $.EventUtils.getTargetByEvent(event)
					if((target.id == "jqg_"+grid.p.id+"_"+rowid && target.type == "checkbox")
						|| (target && ($(target).attr('actionType') == 'delete' || $(target).attr('actionType') == 'custom'))){
						
					}else{
						_this.jqGrid("openEditWindow");
					}
				}
				else {
					if (rowid && grid.p.dblClickRowOpenEditWindow == false) {
						grid.p.enabledValidateForm = true;
						$.jqValidator.setIsShowValidateMsg(grid.p.editFormSelector,true);
						_this.jqGrid('GridToForm', rowid, grid.p.editFormSelector);
					}
				}
			}else if(selected === false){ //反选
				if(grid.p.editFormSelector){
					//重置编辑表单
					$(grid.p.editFormSelector).trigger("reset");
					//1.2.屏蔽验证
					grid.p.enabledValidateForm = false;
				}
				//1.3不允许多行选中时,selected == false 则反选全部
				if(!grid.p.multiselect && grid.p.multiboxonly===true){
					_this.jqGrid('resetSelection');
				}else{
					_this.jqGrid('resetSelection',rowid);
				}
			}
			//3.行点击后事件
			if($.isFunction(grid.p.afterSelectRow)){
				grid.p.afterSelectRow.call(grid,rowid,selected);
			}
		},
		/**
		 * 点击分页按钮时的事件
		 */
		onPaging : function(onpaging){
			var grid = this,ret = true;
			//1.翻页前事件
			if($.isFunction(grid.p.beforePaging)){
				ret = grid.p.beforePaging.call(grid);
			}
			//alert($.objToJSONString(grid.p.postData));
			if(!ret){
				return "stop";
			}else{
				return ret;
			}
		},
		/**
		 * 发送获取数据请求前(ajax 已声明但未请求)
		 */
		loadBeforeSend : function(xhr, settings){
			var grid = this;
			
			var page = grid.p.page;
			grid.p.page = 0;
			grid.updatepager(false, false);
			grid.p.page = page;
			return grid.p.enabledLoad;
		},
		/**
		 * 数据已经load后,表格已完成
		 */
		gridComplete : function (){
			var grid = this,_this = $(this);
			//默认不激活验证表单
			grid.p.enabledValidateForm = false;
			//按钮状态
			_this.jqGrid('refreshButtonStatus');
			//表格完成后事件
			if($.isFunction(grid.p.afterGridCompleteFunc)){
				grid.p.afterGridCompleteFunc.call(grid);
			}
			//add by baodk 对分页按钮加图标
			if($("#"+grid.p.id+"_toppager_"+grid.p.pagerpos)){
				$("#" + grid.p.id + "_toppager_"+grid.p.pagerpos).find("#first_t_"+grid.p.id+"_toppager").attr("title", $.jgrid.paging.firstBtn);
				$("#" + grid.p.id + "_toppager_"+grid.p.pagerpos).find("#prev_t_"+grid.p.id+"_toppager").attr("title", $.jgrid.paging.prevBtn);
				$("#" + grid.p.id + "_toppager_"+grid.p.pagerpos).find("#next_t_"+grid.p.id+"_toppager").attr("title", $.jgrid.paging.nextBtn);
				$("#" + grid.p.id + "_toppager_"+grid.p.pagerpos).find("#last_t_"+grid.p.id+"_toppager").attr("title", $.jgrid.paging.lastBtn);
			}
			
			if($("#"+grid.p.id+"_pager_"+grid.p.pagerpos)){
				$("#" + grid.p.id + "_pager_"+grid.p.pagerpos).find("#first_" + grid.p.id + "_pager").attr("title",  $.jgrid.paging.firstBtn);
				$("#" + grid.p.id + "_pager_"+grid.p.pagerpos).find("#prev_" + grid.p.id + "_pager").attr("title", $.jgrid.paging.prevBtn);
				$("#" + grid.p.id + "_pager_"+grid.p.pagerpos).find("#next_" + grid.p.id + "_pager").attr("title", $.jgrid.paging.nextBtn);
				$("#" + grid.p.id + "_pager_"+grid.p.pagerpos).find("#last_" + grid.p.id + "_pager").attr("title", $.jgrid.paging.lastBtn);
			}
		},
		/**
		 * grid查询请求成功后,处理数据前
		 */
		beforeProcessing : function (data, st, xhr){
			var grid = this;
			//1.加载数据后(响应为success)
			if(data){
				//重新查询必须清空
				grid.p.originalDatas = {};
				grid.p.gridDatasStore = [];
				//原始数据
				grid.p.originalDatas = $.extend({},data);
				//grid的实际数据存储
				for(var i=0;i<data.list.length;i++){
					grid.p.gridDatasStore.push($.extend({},data.list[i]));
				}
				
				//TODO：实体数据类型(所有日期字段的类型)
				//1.one to many子表的日期字段类型
				//2.many to one主表的日期字段类型
				//例：Student的字段数据类型结构
				//	"storeMetaData":{
				//		"createdDtmLoc":"date",
				//		"clazz":{"createdDtmLoc":"date","updatedDtmLoc":"date"},
				//		"studentSubjects":{"createdDtmLoc":"date","updatedDtmLoc":"date"},
				//		"updatedDtmLoc":"date",
				//		"birthday":"date"}
				//	}
				$.extend(grid.p.cmOriginalDataType,data.storeMetaData);
			}
			//2.加载数据后(自定义方法)
			if($.isFunction(grid.p.afterLoad)){
				grid.p.afterLoad.call(grid,data.list,data);
			}
		},
		/**
		 * grid提交查询请求前
		 */
		beforeRequest : function (){
			var grid = this,_this = $(this);
			
			//3.originalDataType 属性的列
			grid.p.cmOriginalDataType = {};
			
			//4.定义动作列数组
			//grid.p.actionColModel = [];//动作列
			grid.p.actionColNames = [];//动作列名称
			grid.p.newBtnAction = {};//新增 按钮的动作
			
			for(var i=0;i<grid.p.colModel.length;i++){
				var cm = grid.p.colModel[i];
				if(cm.actionType && cm.actionType.length > 0){
					//收集动作列名称
					grid.p.actionColNames.push(cm.name);
					//收集动作列
					//grid.p.actionColModel.push(cm);
					//3.2.编辑动作列
					if(cm.actionType == "edit"){
						var tabId,tabTitle;
						//新tab 的标题
						tabTitle = cm.tabTitle
						if(tabTitle == undefined || tabTitle.length < 1)
							tabTitle = $.jgrid.edit.editCaption;
						
						//新tab 的ID
						tabId = cm.tabId
						if(tabId == undefined || tabId.length < 1)tabId = grid.p.jsonReader.id;
						
						//配置 新增按钮 动作,和编辑列动作统一
						grid.p.newBtnAction = {tabTitle:tabTitle,tabId:tabId,actionTarget:cm.actionTarget,actionUrl:cm.actionUrl};
						if(!$.isEmptyObject(grid.p.newBtnActionConfig)){
							//如果newBtnActionConfig不为空,则以newBtnActionConfig配置的动作为准
							$.extend(grid.p.newBtnAction,grid.p.newBtnActionConfig);
						}
					}
				}
				//2.1.获取有originalDataType 的列
				if(cm.originalDataType && cm.originalDataType.length > 0){
					$.extend(grid.p.cmOriginalDataType,$.parseJSON('{"'+cm.name+'":"'+cm.originalDataType+'"}'));
				}
			}

			//重新调整Grid宽度
			_this.jqGrid("resetGridWidth");
			
			//1.加载数据前
			if($.isFunction(grid.p.beforeLoad)){
				if(!grid.p.beforeLoad.call(grid))
					return false;
			}
			//2.先将已配置的queryInfo 转换成对象
			var gridQueryInfo = $.extend({fields:[]},$.parseJSON(grid.p.postData.queryInfo),{fields:[]});
			//3.自定义QueryInfo
			if($.isFunction(grid.p.setQueryInfo)){
				//3.1.再将自定义的queryInfo追加进去
				$.extend(gridQueryInfo,grid.p.setQueryInfo.call(grid));
			}
			
			//5.将调用setQueryInfoFields 时组装的fields 设置为自定义的
			if($.isArray(grid.p.customFields) && grid.p.customFields.length > 0){
				Array.prototype.push.apply(gridQueryInfo.fields,grid.p.customFields);
				//清除搜索表单的条件(每次会传入新的)
				grid.p.customFields = [];
			}
			//6.搜索去组装的fields
			if($.isArray(grid.p.searchFields) && grid.p.searchFields.length > 0){
				Array.prototype.push.apply(gridQueryInfo.fields,grid.p.searchFields);
			}
			//将分页数据追加到queryInfo
			gridQueryInfo.pageSize = _this.jqGrid("getPageSize");
			gridQueryInfo.pageStart = _this.jqGrid("getPageStart");
			//7.queryInfo 转换成为字符串
			var queryInfoJsonStr = $.objToJSONString(gridQueryInfo);
			$.extend(grid.p.postData,{queryInfo:queryInfoJsonStr});
//			alert($.objToJSONString(grid.p.postData));
			
			//add by baodk 初始化内置信息提示框
			if(!$.isFunction(grid.p.afterSave) || !$.isFunction(grid.p.afterDelete)){
				if($("#"+grid.p.id+"MessageDialog").dialog("isOpen") === false){
				}else{
					$("<div>").attr("id", grid.p.id+"MessageDialog").dialog({
						modal:false,
						height:100,
						resizable:false,
						show:$.ui.effects.dialog.show,
						hide:$.ui.effects.dialog.hide,
						autoOpen:false
					}).bind( "dialogopen", function(event, ui) {
						$("#"+grid.p.id+"MessageDialog").parent().fadeOut(grid.p.messageDialogCycleTime,function(){
							$("#"+grid.p.id+"MessageDialog").dialog("close");
						});
					});
				}
			}
			return true;
		},
		/**
		 * 全选事件
		 */
		onSelectAll : function (ids,checked){
			var grid = this,_this = $(this);
			//1.反选
			if(!checked){
				//清空编辑表单
				$(grid.p.editFormSelector).trigger("reset");
				//取消所有选择行的状态
				_this.jqGrid('resetSelection');
				//去除当前选中行
				_this.jqGrid("setGridAttribute",{"selrow":""});
				//关闭校验(防止再点击行时,出现校验)
				grid.p.enabledValidateForm=false;
			}else{
				//清空编辑表单
				$(grid.p.editFormSelector).trigger("reset");
			}
			//按钮状态
			_this.jqGrid('refreshButtonStatus');
			if($.isFunction(grid.p.afterSelectAllFunc)){
				grid.p.afterSelectAllFunc.call(grid, ids, checked);
			}
		},
		/**
		 * 单元格变为可编辑前事件
		 * TODO:jqGrid 内部在调用beforeEditCell时,不需要返回true或false;
		 * 这里返回是控制后续代码不用反复执行.不影响afterEditCell的执行
		 */
		beforeEditCell : function(rowId,colName,cellValue,cellRowIndex,cellColIndex){
			var grid = this,_this = $(this);
			//防止重复点击相同单元格
			if(cellRowIndex == grid.p.iRow && cellColIndex == grid.p.iCol){
				return false;
			}
			else if(cellRowIndex == grid.p.iRow){
				return false;
			}
			return true;
		},
		/**
		 * 单元格变为可编辑状态后事件
		 */
		afterEditCell : function(rowId,colName,cellValue,cellRowIndex,cellColIndex){
			var grid = this,_this = $(this);
			if(grid.p.cellEdit === true){
				//将单元格数据全选
				var cellId = cellRowIndex + "_"+colName;
				function cellSelectAll(){
					$("#"+cellId).select();
					window.clearTimeout(_selectAllTimeObj);
				}
				var _selectAllTimeObj = window.setTimeout(cellSelectAll,0);
			}
			if($.isFunction(grid.p.afterEditCellFunc)){
				grid.p.afterEditCellFunc.call(grid,rowId,colName,cellValue,cellRowIndex,cellColIndex);
			}
		},
		/**
		 * 点击单元格(只在当前单元格为不可编辑时响应)
		 */
		onSelectCell : function(rowId,colName,cellValue,cellRowIndex,cellColIndex){
			var grid = this,_this = $(this);
		},
		/**
		 * 单元格结束编辑，回复到不可编辑状态后事件
		 */
		afterSaveCell : function(rowId,colName,cellValue,cellRowIndex,cellColIndex){
			var grid = this,_this = $(this);
			var rowObj = _this.jqGrid("getRowDataById",rowId);
			if(rowId && rowObj.rowStatus == Gfa.GlobalConstant.ROWSTATUS_UNCHANGED){
				//将行数据改为修改状态
				$.extend(rowObj,{rowStatus:Gfa.GlobalConstant.ROWSTATUS_MODIFIED});
				//填充到表格
				_this.jqGrid('setRowData',rowId,$.extend({},rowObj,$.parseJSON('{"'+colName+'":"'+cellValue+'"}')));
			}
			//按钮状态
			_this.jqGrid('refreshButtonStatus');
			//单元格结束编辑，回复到不可编辑状态后事件
			if($.isFunction(grid.p.afterSaveCellFunc)){
				grid.p.afterSaveCellFunc.call(grid,rowId,colName,cellValue,cellRowIndex,cellColIndex);
			}
		},
		/**
		 * 数据插入表格后事件.(addRowData的内部事件)
		 */
		afterInsertRow : function(rowId, rowData,temp){
			var grid = this,_this = $(this);
//			alert($.objToJSONString(temp));
			if($.isFunction(grid.p.afterInsertRowFunc)){
				grid.p.afterInsertRowFunc.call(grid,rowId, rowData);
			}
			//数据插入表格后，同时同步到grid store
			_this.jqGrid("setGridDatasStoreById",rowId,rowData);
		},
		/**
		 * 加载失败事件
		 */
		loadError:function(xhr,st,err){
			var grid = this,_this = $(this);
			if(xhr.status==500){
				var responseObj =$.parseJSON(xhr.responseText) ;
				if($.isPlainObject(responseObj) && !$.isEmptyObject(responseObj)){
					$("#"+grid.p.id+"MessageDialog").html(responseObj.errorMsg)
						.dialog("option","title", $.jgrid.initMessageTag.loadErrorTag)
						.dialog("open");
				}
			}else{
				$("#"+grid.p.id+"MessageDialog").html(err)
					.dialog("option","title", $.jgrid.initMessageTag.loadErrorTag)
					.dialog("open");
			}
		}
	});
})(jQuery);